﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace H2.NET.Web.Pages.SMD
{
    public partial class ChangeDevice : BasePage
    {
        private int storeid = 0;
        private bool noDevice = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            DwzAssessment1.Category = "ChangeDevice";
            storeid = TaskAPI.GetStoreId("storeid");

            t_smd_Device hasdevice = (t_smd_Device._StoreID == storeid).ListFirst<t_smd_Device>(Storage.Context3);

            if (hasdevice == null)
            {
                if(storeid != 0)
                    noDevice = true;

                tb_DeviceInfo.Visible = false;
                
            }

            if (!IsPostBack)
            {
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }
                btn_submit.Visible = TaskAPI.IsAllowSubmit;
                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                InitDropDownList();

                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);

                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);

                #region Submit Data
                if (TaskAPI.Step == "Submit Data")
                {
                    tb_changelogs.Visible = false;
                    var store = new t_smd_Store();
                    var device = new t_smd_Device();
                    var devices = new List<t_smd_Device>();
                    // 不为空，就是退回的
                    var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");
                    if (!string.IsNullOrEmpty(blankVlue))
                    {
                        uc_store_info1.IsCanEditAuthID = false;
                        var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");
                        store = StoreService.GetSmdStoreById(storeid);
                        device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));
                        devices = DeviceService.FindByStoreId(storeid);
                    }
                    else
                    {
                        uc_store_info1.IsCanEditAuthID = true;
                        store = StoreService.GetSmdStoreById(storeid);
                        devices = (t_smd_Device._StoreID == store.StoreID).List<t_smd_Device>(Storage.Context3).ToList();
                        if (devices != null && devices.Count > 0)
                        {
                            device = devices[0];
                        }
                    }

                    uc_store_info1.store = store;
                    BindControl(device, true);

                    ddl_FullSetSN.AppendDataBoundItems = true;
                    ddl_FullSetSN.DataSource = devices;
                    ddl_FullSetSN.DataTextField = "FullSetSN";
                    ddl_FullSetSN.DataValueField = "DeviceId";
                    ddl_FullSetSN.DataBind();

                    ddl_FullSetSN.SelectedValue = device.DeviceID.ToString();

                    if (noDevice) 
                    {
                        JsTip(string.Format("该门店没有设备不能发起设备数据变更！"));
                        btn_submit.Visible = false;
                        return;
                    }
                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        assessment.Visible = true;
                        var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");
                        device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));

                        var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                        device = DataHelper<t_smd_Device>.Reload(device, changelogs);
                        BindControl(device, true);
                    }
                }
                #endregion

                #region 审批环节
                else
                {
                    t_StoreMasterData storeMasterData = (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).ListFirst<t_StoreMasterData>();
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;

                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                    #region Data Check 、 Manager Approve
                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");

                        var store = StoreService.GetSmdStoreById(storeid);
                        var devices = DeviceService.FindByStoreId(store.StoreID);
                        var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));

                        var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                        device = DataHelper<t_smd_Device>.Reload(device, changelogs);

                        uc_store_info1.store = store;
                        uc_store_info1.IsCanEditAuthID = false;
                        uc_change_field1.AssessmentIDs = assIds;

                        BindControl(device, true);
                        ddl_FullSetSN.Visible = false;
                        l_FullSetSNList.Text = device.FullSetSN;
                    }
                    #endregion
                    else
                    {
                        #region 加载数据并显示

                        var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");

                        var store = StoreService.GetSmdStoreById(storeid);
                        var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));

                        var changelogs = ChangeLogService.GetLastChangeLogs(assIds);
                        device = DataHelper<t_smd_Device>.Reload(device, changelogs);
                        BindControl(device, false);
                        assessment.Visible = true;

                        uc_store_info1.store = store;
                        uc_store_info1.IsCanEditAuthID = false;
                        uc_change_field1.AssessmentIDs = assIds;

                        ddl_FullSetSN.Visible = false;
                        l_FullSetSNList.Text = device.FullSetSN;

                        #endregion

                        #region 审批项初始化
                        switch (TaskAPI.Step)
                        {
                            case "DMO Commit":
                                DwzAssessment1.Category = null;
                                break;
                        }
                        #endregion
                    }
                }
                #endregion
            }
        }

        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);
                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");
                var store = StoreService.GetSmdStoreById(storeid==0?storeMasterData.StoreId.Value:storeid);
                var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));
                var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                device = DataHelper<t_smd_Device>.Reload(device, changelogs);

                BindControl(device, false);

                uc_store_info1.store = store;
                uc_store_info1.IsCanEditAuthID = false;
                uc_change_field1.AssessmentIDs = assIds;

                ddl_FullSetSN.Visible = false;
                l_FullSetSNList.Text = device.FullSetSN;

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string return_msg)
        {
            bool flag = false;
            try
            {
                var _dealer = DealerService.GetById(uc_store_info1.store.DealerID.Value);

                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    if (storeid == 0)
                    {
                        return_msg = "请选择门店";
                        return false;
                    }

                    if (string.IsNullOrEmpty(ddl_FullSetSN.SelectedValue))
                    {
                        return_msg = "请选择设备";
                        return false;
                    }
                }
                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }
                #endregion

                #region 引擎传值
                if (TaskAPI.Step == "Submit Data")
                {
                    TaskAPI["BlankVlue"] = storeid;
                    TaskAPI["DeviceID"] = ddl_FullSetSN.SelectedValue;
                    var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(ddl_FullSetSN.SelectedValue,0));
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI.Summary = "设备信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        assessment.Visible = true;
                    }
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(TaskAPI.GetVariableBySingleValue("DeviceID"), 0));
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "设备信息CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                        }
                        else
                        {
                            TaskAPI.Summary = "(退回)提交设备信息变更/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                        }
                    }
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "设备变更DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                        }
                        else
                        {
                            TaskAPI.Summary = "(退回)设备信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                        }
                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        return_msg = "数据更新到主数据库中时出现错误，请跟踪并处理。";
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)设备信息CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                        }

                    }
                }

                #endregion

                #region 提交步骤
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        t_StoreMasterData storeMasterData = new t_StoreMasterData();
                        storeMasterData.SubmitDate = DateTime.Now;
                        storeMasterData.Creator = TaskAPI.UserName;
                        storeMasterData.ApplicationNO = uc_head1.applicationNo;
                        storeMasterData.Process = TaskAPI.Process;
                        storeMasterData.Incident = TaskAPI.Incident;
                        storeMasterData.StoreId = storeid;
                        storeMasterData.BusinessProcess = ass.BusinessProcess;
                        storeMasterData.BusinessKey = ass.BusinessKey;
                        Storage.Save(Storage.Context1, storeMasterData);

                        // 记录变更日志
                        var changelogs = SaveChangeLog(Utils.StrToInt(ddl_FullSetSN.SelectedValue, 0), ass.ID);

                        if (changelogs.Count == 0)
                        {
                            throw new Exception("对不起，数据无任何修改，提交失败");
                        }

                        Storage.Save(Storage.Context1, changelogs.ToArray());

                        if (key.Equals(Constant.PROCESS_CHANGEOTHER))
                        {
                            BusinessService.SaveChildProcess(TaskAPI, ass, "active");
                            var store = StoreService.GetSmdStoreById(storeid);
                            var dealer = DealerService.GetById(store.DealerID.Value);
                            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(ddl_FullSetSN.SelectedValue, 0));
                            BusinessService.saveProcessRelation(TaskAPI, ass, store, device, dealer, null, null, null, null);
                            if (key == Constant.PROCESS_CHANGEOTHER && !TaskAPI.Summary.Contains("退回"))
                            {
                                TaskAPI.Summary = "设备信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "-" + ass.BusinessKey + "|" + device.FullSetSN + "|" + uc_store_info1.store.AuthID + "|" + _dealer.DealerCode;
                            }
                        }

                        
                    }
                    #endregion

                    #region “Data Check”步骤
                    if (TaskAPI.Step == "Data Check")
                    {
                        // 记录变更日志
                        var changelogs = SaveChangeLog(Utils.StrToInt(ddl_FullSetSN.SelectedValue, 0), ass.ID);
                        Storage.Save(Storage.Context1, changelogs.ToArray());
                    }
                    #endregion

                    #region “Manager Approve”步骤
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        // 记录变更日志
                        var changelogs = SaveChangeLog(Utils.StrToInt(ddl_FullSetSN.SelectedValue, 0), ass.ID);

                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            // 将变更日志转移至smd数据库
                            var smd_changelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());

                            // 获取业务数据主键
                            var id = smd_changelogs[0].DataID;
                            // 获取原始门店数据
                            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(id, 0));
                            // 根据变更日志重新加载门店信息
                            device = DataHelper<t_smd_Device>.Reload(device, smd_changelogs);
                            // 更新门店信息
                            Storage.Save(Storage.Context3, device);

                            // 更新业务数据状态
                            StoreMasterDataService.UpdateFinish(TaskAPI);
                            BusinessService.saveProcessRelation(TaskAPI, ass, null, device, null, null, null, null, null);
                            BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                           //新增businesskey
                            var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            BusinessService.SaveSycnMappingAndBusinesskey(3, masterStore.BusinessKey); 


                        }
                        else if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                    }
                    #endregion
                });

                if (DwzAssessment1.Assessment.Opinion != "2")
                {
                    // 变更列表
                    TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                    flag = TaskAPI.Send();
                }
                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用ChangeDevice.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        #region 绑定各选项
        private void InitDropDownList()
        {
            ConfigService configService = new ConfigService();
            #region 设备信息

            #region 调色机型号
            DataTable dt_dispenseModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_TSJLX') order by seq").Tables[0];
            ddl_DispenserModel.AppendDataBoundItems = true;
            //ddl_dispenseModel.Items.Add(new ListItem("无需机器", ""));
            foreach (DataRow row in dt_dispenseModel.Rows)
            {
                ddl_DispenserModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 震荡机型号
            DataTable dt_shakerModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_ZDJLX') order by seq").Tables[0];
            ddl_ShakerModel.AppendDataBoundItems = true;
            //ddl_shakerModel.Items.Add(new ListItem("无需机器", ""));
            foreach (DataRow row in dt_shakerModel.Rows)
            {
                ddl_ShakerModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 电脑型号
            DataTable dt_PcModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DNXH') order by seq").Tables[0];
            ddl_PcModel.AppendDataBoundItems = true;
            //ddl_PcModel.Items.Add(new ListItem("无需电脑", ""));
            foreach (DataRow row in dt_PcModel.Rows)
            {
                ddl_PcModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 设备状态
            DataTable dt_Status = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBZT') and name not in ('公司大仓','经销商处寄存','报废','E-approve导入无状态','CRM导入无状态') order by seq").Tables[0];
            Status.AppendDataBoundItems = true;
            foreach (DataRow row in dt_Status.Rows)
            {
                Status.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion
            
            #region 发放方式
            DataTable dt_DeliveryType = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_FFFS') order by seq").Tables[0];
            DeliveryType.AppendDataBoundItems = true;
            foreach (DataRow row in dt_DeliveryType.Rows)
            {
                DeliveryType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion
            #endregion

        }
        #endregion

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
                return;
            }
            else
            {
                return_msg = string.IsNullOrEmpty(return_msg) ? Resources.Global.C_00_Failed : return_msg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
                return;
            }
        }

        private void BindControl(t_smd_Device device, bool isCanEdit)
        {
            string key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            if (isCanEdit)
            {
                #region 如果是手动发起的
                if (key == "")
                {
                    ddl_DispenserModel.Visible = false;
                    tb_DispenserFixedAsset.Visible = false;
                    tb_DispenserSN.Visible = false;

                    ddl_ShakerModel.Visible = false;
                    tb_ShakerFixedAsset.Visible = false;
                    tb_ShakerSN.Visible = false;

                    ddl_PcModel.Visible = false;
                    tb_PcFixedAsset.Visible = false;
                    tb_PcSN.Visible = false;

                    FullSetSN.Visible = false;
                    MeiPinNo.Visible = false;
                    IsTurnSolid1.Visible = false;
                    IsTurnSolid2.Visible = false;
                    DeliveryType.Visible = false;
                    InstallDate.Visible = false;


                    l_FullSetSN.Text = device.FullSetSN;
                    l_MeiPinNo.Text = device.MeiPinNo;
                    l_IsTurnSolid.Text = device.IsTurnSolid ? "是" : "否";
                    l_DeliveryType.Text = device.DeliveryType;
                    l_InstallDate.Text = device.InstallDate == null ? "" : device.InstallDate.Value.ToString("yyyy-MM");
                    PurchasedDate.Text = device.PurchasedDate == null ? "" : device.PurchasedDate.Value.ToString("yyyy");
                    l_DispenserModel.Text = device.DispenserModel;
                    l_DispenserFixedAsset.Text = device.DispenserFixedAsset;
                    l_DispenserSN.Text = device.DispenserSN;

                    l_ShakerModel.Text = device.ShakerModel;
                    l_ShakerFixedAsset.Text = device.ShakerFixedAsset;
                    l_ShakerSN.Text = device.ShakerSN;

                    l_PcModel.Text = device.PcModel;
                    l_PcFixedAsset.Text = device.PcFixedAsset;
                    l_PcSN.Text = device.PcSN;
                }
                #endregion

                Status.Enabled = false;
                Status.Visible = false;
                l_Status.Text = device.Status;
                FullSetSN.Text = device.FullSetSN;
                MeiPinNo.Text = device.MeiPinNo;
                if (device.IsTurnSolid)
                {
                    IsTurnSolid1.Checked = true;
                }else{
                    IsTurnSolid2.Checked = true;
                }
                DeliveryType.SelectedValue = device.DeliveryType;
                PurchasedDate.Text = device.PurchasedDate == null ? "" : device.PurchasedDate.Value.ToString("yyyy");
                InstallDate.Text = device.InstallDate == null ? "" : device.InstallDate.Value.ToString("yyyy-MM");

                ddl_DispenserModel.SelectedValue = device.DispenserModel;
                tb_DispenserFixedAsset.Text = device.DispenserFixedAsset;
                tb_DispenserSN.Text = device.DispenserSN;

                ddl_ShakerModel.SelectedValue = device.ShakerModel;
                tb_ShakerFixedAsset.Text = device.ShakerFixedAsset;
                tb_ShakerSN.Text = device.ShakerSN;
                tb_Address.Text = device.Address;

                ddl_PcModel.SelectedValue = device.PcModel;
                tb_PcFixedAsset.Text = device.PcFixedAsset;
                tb_PcSN.Text = device.PcSN;
            }
            else
            {
                l_Status.Text = device.Status;
                l_FullSetSN.Text = device.FullSetSN;
                l_MeiPinNo.Text = device.MeiPinNo;
                l_IsTurnSolid.Text = device.IsTurnSolid?"是":"否";
                l_DeliveryType.Text = device.DeliveryType;
                l_PurchasedDate.Text = device.PurchasedDate == null ? "" :device.PurchasedDate.Value.ToString("yyyy");
                l_InstallDate.Text = device.InstallDate == null ? "" : device.InstallDate.Value.ToString("yyyy-MM");

                l_DispenserModel.Text = device.DispenserModel;
                l_DispenserFixedAsset.Text = device.DispenserFixedAsset;
                l_DispenserSN.Text = device.DispenserSN;

                l_ShakerModel.Text = device.ShakerModel;
                l_ShakerFixedAsset.Text = device.ShakerFixedAsset;
                l_ShakerSN.Text = device.ShakerSN;

                l_PcModel.Text = device.PcModel;
                l_PcFixedAsset.Text = device.PcFixedAsset;
                l_PcSN.Text = device.PcSN;
                l_Address.Text = device.Address;

                ddl_DispenserModel.Visible = false;
                tb_DispenserFixedAsset.Visible = false;
                tb_DispenserSN.Visible = false;

                ddl_ShakerModel.Visible = false;
                tb_ShakerFixedAsset.Visible = false;
                tb_ShakerSN.Visible = false;

                ddl_PcModel.Visible = false;
                tb_PcFixedAsset.Visible = false;
                tb_PcSN.Visible = false;

                Status.Visible = false;
                FullSetSN.Visible = false;
                MeiPinNo.Visible = false;
                IsTurnSolid1.Visible = false;
                IsTurnSolid2.Visible = false;
                DeliveryType.Visible = false;
                PurchasedDate.Visible = false;
                InstallDate.Visible = false;
                tb_Address.Visible = false;
            }
        }

        private List<t_StoreDataChangeLog> SaveChangeLog(int deviceid, string assid)
        {
            var existing_changelogs = ChangeLogService.GetLastChangeLogs(TaskAPI);

            var device = DeviceService.GetSmdDeviceById(deviceid);
            if (device == null) device = new t_smd_Device();
            DataHelper<t_smd_Device>.Reload(device, existing_changelogs);

            var new_device = (t_smd_Device)device.CloneObject();
            new_device.Status = Status.SelectedValue;
            if (!string.IsNullOrEmpty(PurchasedDate.Text))
            {
                new_device.PurchasedDate = Utils.StrToDateTimeN(PurchasedDate.Text + "-1-1");
            }
            new_device.Address = tb_Address.Text;

            var changelogs = DataHelper<t_smd_Device>.GetChangeLogs(device, new_device,
                new_device.GetChangeFields(), "DeviceID", UserAPI.UserFullName, assid, "ChangeDevice");

            return ChangeLogService.GetDistinctChangeLogs(changelogs, existing_changelogs);
        }

        protected void ddl_FullSetSN_SelectedIndexChanged(object sender, EventArgs e)
        {
            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(ddl_FullSetSN.SelectedValue, 0));
            BindControl(device, true);
        }
    }
}